package com.qxjc.manage.web.park;

import java.io.File;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.apache.commons.io.FileUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.qxjc.manage.entity.WorkflowParam;
import com.qxjc.manage.pojo.ParkApplyImage;
import com.qxjc.manage.pojo.ParkApplyInfo;
import com.qxjc.manage.pojo.User;
import com.qxjc.manage.service.ParkService;
import com.qxjc.manage.service.WorkflowService;



@Controller
@RequestMapping("/workflow")
public class WorkFlowController {
	

	@Autowired
	private WorkflowService workflowService;

	@Autowired
	private ParkService  parkService;
	

	/**
	 * 	部署流程定义
	 * Title: newdeploye
	 * Description:
	 * @param @param request
	 * @param @param files
	 * @param @param filename 
	 * @return void
	 */
	@PostMapping("/upload")
	public ModelAndView newdeploy(HttpServletRequest request, @RequestParam("file") MultipartFile files,
			@RequestParam("filename") String filename) {
		try {
			String path = request.getSession().getServletContext().getRealPath("/upload/");
			String suffix = files.getOriginalFilename().substring(files.getOriginalFilename().lastIndexOf("."));
			String fileName = UUID.randomUUID().toString() + suffix;
			File f = File.createTempFile(path, fileName);
			files.transferTo(f);
			workflowService.saveNewDeploye(f, filename);
			if (f.isDirectory()) {
				FileUtils.deleteDirectory(f);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ModelAndView("redirect:/workflow/deployHome");
	}

	/**
	 * 部署管理首页显示
	 * Title: deployHome
	 * Description:
	 * @param @param map
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/deployHome")
	public ModelAndView deployHome(Map<String, Object> map){
		//1:查询部署对象信息，对应表(act_re_deployment)
		List<Deployment> depList = workflowService.findDeploymentList();
		//2:查询流程定义的信息，对应表(act_re_procdef)
		List<ProcessDefinition> pdList = workflowService.findProcessDefinitionList();
		
		map.put("depList", depList);
		map.put("pdList", pdList);
		return new ModelAndView("/park/workflow/index",map);
		}
	
	
	/**
	 * 删除部署信息
	 * Title: delDeployment
	 * Description:
	 * @param @param deploymentId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/delete")
	public ModelAndView delDeployment(@RequestParam("deploymentId") String deploymentId){
		
		workflowService.deleteProcessDefinitionByDeploymentId(deploymentId);
		return new ModelAndView("redirect:/workflow/deployHome");
	}
	
	/**
	 * 初始化流程图
	 * Title: viewInit
	 * Description:
	 * @param @param deploymentId
	 * @param @param imageName
	 * @param @param map
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/vinit")
	public  ModelAndView viewInit(@RequestParam("deploymentId") String deploymentId,
							 @RequestParam("imageName") String imageName,
						Map<String , Object> map){
		map.put("deploymentId", deploymentId);
		map.put("imageName", imageName);
		return new ModelAndView("/park/workflow/view",map);
	}
	
	/**
	 * 查看流程图
	 * Title: viewImage
	 * Description:
	 * @param @return 
	 * @return String
	 * @throws Exception 
	 */
	@RequestMapping("/view")
	public  String viewImage(@RequestParam("deploymentId") String deploymentId,
							 @RequestParam("imageName") String imageName,
							HttpServletResponse response) throws Exception{
		//获取资源文件表（act_ge_bytearray）中资源图片输入流InputStream
		InputStream inputStream  = workflowService.findImageInputStream(deploymentId,imageName);
		response.setHeader("Content-Type","image/jped");//设置响应的媒体类型，这样浏览器会识别出响应的是图片
		for(int b=-1;(b=inputStream.read())!=-1;){
			response.getOutputStream().write(b);
		}
		response.flushBuffer();
		inputStream.close();
		return null;
	}
	
	/**
	 * 启动流程
	 * Title: startProcess
	 * Description:
	 * @param @param id
	 * @param @param request
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("start/{id}")
	public ModelAndView startProcess(@PathVariable("id") String id,HttpServletRequest request){
		User existUser = (User) SecurityUtils.getSubject().getPrincipal();
		String username = existUser.getUsername();
		//更新请假状态，启动流程实例，让启动的流程实例关联业务
		workflowService.startProcess(id,username);
		return new ModelAndView("redirect:/workflow/listTask");
	}
	
	/**
	 * 任务管理首页显示
	 * Title: listTask
	 * Description:
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/listTask")
	public ModelAndView listTask(HttpServletRequest request,Map<String,Object> map){
		User existUser = (User) SecurityUtils.getSubject().getPrincipal();
		String username = existUser.getUsername();
		List<Task> tasks = workflowService.findTaskListByName(username);
		map.put("tasks", tasks);
		return new ModelAndView("/park/workflow/task",map);
	}
	
	/**
	 * 打开任务表单
	 * Title: viewTaskForm
	 * Description:
	 * @param @param taskId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/viewTaskForm")
	public ModelAndView viewTaskForm(@RequestParam("taskId") String taskId){
		String url = workflowService.findTaskFormKeyByTaskId(taskId);
		url +="?taskId="+taskId;
		return new ModelAndView("redirect:"+url);
	}
	
	
	/**
	 * 准备表单数据
	 * Title: audit
	 * Description:
	 * @param @param taskId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/audit")
	public ModelAndView audit(@RequestParam("taskId")String taskId,
							  Map<String, Object> map){
		/**一：使用任务ID，查找请假单ID，从而获取请假单信息*/
		ParkApplyInfo applyInfo = workflowService.findApplyInfoByTaskId(taskId);
		ParkApplyImage applyImage = parkService.selectParkApplyImageById(applyInfo.getApplyImgId());
		map.put("applyInfo", applyInfo);
		map.put("applyImage", applyImage);
		map.put("taskId", taskId);
		/**二：已知任务ID，查询ProcessDefinitionEntiy对象，从而获取当前任务完成之后的连线名称，并放置到List<String>集合中*/
		List<String> outcomeList = workflowService.findOutComeListByTaskId(taskId);
		map.put("outcomeList", outcomeList);
		/**三：查询所有历史审核人的审核信息，帮助当前人完成审核，返回List<Comment>*/
		List<Comment> commentList = workflowService.findCommentByTaskId(taskId);
		map.put("commentList", commentList);
		return new ModelAndView("/park/workflow/taskForm",map);
		}
	
	/**
	 * 提交任务
	 * Title: submitTask
	 * Description:
	 * @param @param workflowForm
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/submitTask")
	public ModelAndView submitTask(@RequestParam String taskId,
								   @RequestParam String outcome,
								   @RequestParam String id,
								   @RequestParam String comment,HttpServletRequest request){
		WorkflowParam workflowParam = new WorkflowParam();
		workflowParam.setComment(comment);
		workflowParam.setTaskId(taskId);
		workflowParam.setOutcome(outcome);
		workflowParam.setId(id);
		User existUser = (User) SecurityUtils.getSubject().getPrincipal();
		String username = existUser.getUsername();
		ParkApplyInfo applyInfo = workflowService.findApplyInfoByTaskId(taskId);
		if (outcome.equals("不同意")) {
			applyInfo.setModified(0);
		}
		if (outcome.equals("同意")) {
			applyInfo.setModified(1);
		}
		parkService.updateParkApplyInfo(applyInfo);
		workflowService.saveSubmitTask(workflowParam,username);
		return new ModelAndView("redirect:/workflow/listTask");
	}
	
	
	
	/**
	 * 查看当前流程图（查看当前活动节点，并使用红色的框标注）
	 * Title: viewCurrentImage
	 * Description:
	 * @param @param taskId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/viewCurrentImage")
	public ModelAndView viewCurrentImage(@RequestParam("taskId")String taskId,
										 Map<String, Object> map){
		/**一：查看流程图*/
		//1：获取任务ID，获取任务对象，使用任务对象获取流程定义ID，查询流程定义对象
		ProcessDefinition pDefinition  = workflowService.findProcessDefinitionByTaskId(taskId);
		map.put("deploymentId", pDefinition.getDeploymentId());
		map.put("imageName", pDefinition.getDiagramResourceName());
		/**二：查看当前活动，获取当期活动对应的坐标x,y,width,height，将4个值存放到Map<String,Object>中*/
		Map<String, Object> acsmap = workflowService.findCoordingByTask(taskId);
		map.put("acs", acsmap);
		return new ModelAndView("/park/workflow/currentImage",map);
	}
	
	/**
	 * 查看历史的批注信息
	 * Title: viewHisComment
	 * Description:
	 * @param @param billId
	 * @param @return 
	 * @return ModelAndView
	 */
	@RequestMapping("/viewHisComment/{id}")
	public ModelAndView viewHisComment(@PathVariable("id")String id,
										Map<String, Object> map){
		
		//1：使用请假单ID，查询请假单对象
		ParkApplyInfo applyInfo = parkService.selectParkApplyInfoById(id);
		ParkApplyImage applyImage = parkService.selectParkApplyImageById(applyInfo.getApplyImgId());
		map.put("applyInfo", applyInfo);
		map.put("applyImage", applyImage);
		if (applyInfo.getState() == 1 &&  applyInfo.getState() == 2) {
			//2：使用请假单ID，查询历史的批注信息
			List<Comment> commentList = workflowService.findCommentByApplyInfoId(id);
			map.put("commentList", commentList);
		}
		return new ModelAndView("/park/workflow/taskFormHis",map);
	}
}


